﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using CRMAdminDashboard.CrmSvc;

namespace CRMAdminDashboard
{
    /// <summary>
    /// Wrapper for CrmSvc.businessunit.
    /// </summary>
    public class BusinessUnit
    {

        #region Properties

        /// <summary>
        /// BusinessUnit's Guid in CRM.
        /// </summary>
        public Guid Id { get; set; }

        /// <summary>
        /// BusinessUnit's Name in CRM.
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Minimum set of attributes to query.
        /// </summary>
        static public ColumnSet BusinessUnitColumnSet { get; set; }

        /// <summary>
        /// The actual CRM object.
        /// </summary>
        public businessunit InnerBusinessUnit;

        #endregion

        #region Entry Points

        /// <summary>
        /// Standard ctor.
        /// </summary>
        public BusinessUnit(businessunit crmBu)
        {
            this.InnerBusinessUnit = crmBu;
            this.Name = crmBu.name;
            this.Id = crmBu.businessunitid.Value;
        }

        /// <summary>
        /// This will make the list box entry look nice
        /// </summary>
        public override string ToString()
        {
            return this.Name;
        }

        /// <summary>
        /// Return all Business Units
        /// </summary>
        public static List<BusinessUnit> GetAllBUs(CachingCrmService svcHandle)
        {
            QueryExpression query = new QueryExpression();
            query.EntityName = EntityName.businessunit.ToString();
            query.ColumnSet = BusinessUnitColumnSet;
            BusinessEntityCollection bus = svcHandle.RetrieveMultiple(query);
            List<BusinessUnit> list = new List<BusinessUnit>();
            foreach (BusinessEntity be in bus.BusinessEntities)
            {
                list.Add(new BusinessUnit((businessunit)be));
            }

            return list;
        }

        #endregion

        #region Local Methods

        /// <summary>
        /// Static initializer
        /// </summary>
        static BusinessUnit()
        {
            BusinessUnitColumnSet = new ColumnSet();
            BusinessUnitColumnSet.Attributes = new string[] { "name" };
        }

        #endregion

    }
}
